package com.lhy.gulimall.search.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.lhy.common.to.es.SkuEsModel;
import com.lhy.gulimall.search.config.ElasticsearchConfig;
import com.lhy.gulimall.search.constant.EsConstant;
import com.lhy.gulimall.search.service.MallSearchService;
import com.lhy.gulimall.search.vo.SearchParam;
import com.lhy.gulimall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam searchParam) {
        // 动态构建出查询需要的DSL语句

        // 准备检索条件
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        SearchResult result = null;

        try {
            // 执行检索请求
            SearchResponse searchResponse = client.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS);

            // 分析响应数据封装成我们需要的格式
            result =  buildSearchResult(searchResponse,searchParam);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 准备检索条件
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam){
        // 构建DSL语句
        SearchSourceBuilder builder = new SearchSourceBuilder();

        /**
         * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 1.1 must
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }

        // 1.2 bool -filter
        // 类型id
        if (null != searchParam.getCatalog3Id()) {
            boolQuery.filter(QueryBuilders.termQuery("catelogId", searchParam.getCatalog3Id()));
        }
        // 品牌id
        if (CollUtil.isNotEmpty(searchParam.getBrandId())) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        // 属性
        if (CollUtil.isNotEmpty(searchParam.getAttrs())) {
            for (String attr : searchParam.getAttrs()) {
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                // attrs=1_5寸:8寸&attrs=2_16G:8G
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个都需要生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }
        // 库存
        if (null != searchParam.getHasStock()) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));

        }
        // 价格区间
        if (null != searchParam.getSkuPrice()) {
            // 区间1_500 小于_500 大于500_
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = searchParam.getSkuPrice().split("_");
            if (s.length == 2) {
                rangeQuery.gte(s[0]).lte(s[1]);
            } else if (s.length == 1) {
                // 小于
                if (searchParam.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(s[0]);
                }
                // 大于
                if ((searchParam.getSkuPrice().endsWith("_"))) {
                    rangeQuery.gte(s[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        builder.query(boolQuery);

        /**
         * 排序，分页，高亮，
         */
        // 排序
        if (StringUtils.isNotBlank(searchParam.getSort())) {
            // sort=hatScore_asc/desc
            String[] s = searchParam.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            builder.sort(s[0], order);
        }
        //分页 (pageNum-1)*pageSzie
        builder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        builder.size(EsConstant.PRODUCT_PAGESIZE);
        //高亮 有模糊检索才高亮
        if (StringUtils.isNotBlank(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        // 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId");
        brand_agg.size(50);

        // 品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(20));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(20));

        builder.aggregation(brand_agg);

        // 类型聚合
        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catelog_agg");
        catelog_agg.field("catelogId");
        catelog_agg.size(50);

        // 类型聚合的子聚合
        catelog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(20));
        builder.aggregation(catelog_agg);

        // 属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");

        // 属性聚合的子聚合
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(20);
        // 属性聚合的子聚合的子聚合
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(20));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);

        builder.aggregation(attr_agg);

        String dsl = builder.toString();
        System.out.println(dsl);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, builder);
        return searchRequest;
    }

    /**
     * 封装返回结果
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse searchResponse,SearchParam searchParam){
        SearchResult result = new SearchResult();
        SearchHits hits = searchResponse.getHits();
        List<SkuEsModel> esModelList = new ArrayList<>();
        if (null != hits.getHits() && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.isNotBlank(searchParam.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }
                esModelList.add(esModel);
            }
        }
        result.setProducts(esModelList);
//        //1、 返回所有查询到的商品
//        result.setProducts();
//
//        // 2、当前所有商品涉及到的所有属性信息
//        result.setAttrs();
        List<SearchResult.AttrVo> attrs = Lists.newArrayList();
        ParsedNested attr_agg = searchResponse.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> buckets = attr_id_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 得到属性的id
            long attr_id = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attr_id);
            // 得到属性的名字
            String attr_name = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attr_name);
            // 得到属性的所有信息
            List<String> attr_values = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(b -> {
                return b.getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrValue(attr_values);
            attrs.add(attrVo);
        }
        result.setAttrs(attrs);
//        // 3、品牌信息
//        result.setBrands();
        List<SearchResult.BrandVo> brandVos = Lists.newArrayList();

        ParsedLongTerms brand_agg = searchResponse.getAggregations().get("brand_agg");
        List<? extends Terms.Bucket> brand_aggBuckets = brand_agg.getBuckets();
        for (Terms.Bucket bucket : brand_aggBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 品牌id
            String brand_id = bucket.getKeyAsString();
            brandVo.setBrandId(Long.parseLong(brand_id));
            // 品牌名字
            String brand_name_agg = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg")).getBuckets().get(0).getKeyAsString();
            // 品牌的图片
            String brand_img_agg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg")).getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brand_name_agg);
            brandVo.setBrandImg(brand_img_agg);
            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);

//        // 4、分类信息
//        result.setCatalogs();
        ParsedLongTerms catelog_agg = searchResponse.getAggregations().get("catelog_agg");
        List<SearchResult.CatalogVo> catalogVos = Lists.newArrayList();
        List<? extends Terms.Bucket> catelog_aggBuckets = catelog_agg.getBuckets();
        for (Terms.Bucket bucket : catelog_aggBuckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 分类id
            String catalog_id = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalog_id));

            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            // 分类名字
            String catalog_name = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalog_name);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
        // 5、分页信息
        result.setPageNum(searchParam.getPageNum());
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        int totalpages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ? (int) total / EsConstant.PRODUCT_PAGESIZE :
                (int) total % EsConstant.PRODUCT_PAGESIZE + 1;
        result.setTotalPages(totalpages);

        List<Integer> pageNavs = Lists.newArrayList();
        for (int i = 1; i <= totalpages; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        // 构建面包屑导航功能
        List<SearchResult.NavVo> navVos = new ArrayList<>();
//        attrs.stream().map(attr -> {
//            //1、分析每隔attrs 传过来的查询参数值
//            SearchResult.NavVo navVo = new SearchResult.NavVo();
////            attr.get
//        })
        result.setNavs(navVos);
        return result;
    }
}
